package resources;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.newdawn.slick.util.Log;


public class ResourceFinder {
	private final String[] EXCLUDED_RESOURCES = new String[]{"ResourceFinder", "resources"};
	private List<String> resources;
	
	public ResourceFinder() {
		resources = new LinkedList<>();
	}

	private void buildPropertiesFile(String string) throws FileNotFoundException, IOException {
		long start = System.currentTimeMillis();
		
		URL url = getClass().getResource("");
		File f = new File(url.getFile());
		
		Log.info("Looking for resources...");
		loadResourceReferences(f);
		
		Properties properties = new Properties();

		System.out.println();
		Log.info("Building properties file...");
		
		for(String resourceRef : resources){
			
			String key = resourceRef.substring(resourceRef.lastIndexOf('\\') + 1, resourceRef.lastIndexOf('.'));
			String value = resourceRef.replace('\\', '/');
			
			if(!isExcluded(key)){
				Log.info("Added to props: " + key + " : " + value);
				properties.put(key, value);
			}
		}
		
		properties.store(new FileOutputStream("res\\resources\\resources.properties"), "Generated on last resource change. Generator written by Grizz :)");
		
		System.out.println();
		Log.info("Properties file built in "+(System.currentTimeMillis()-start)+"ms");
	}

	private void loadResourceReferences(File node){
		if(node.isDirectory()){
			String[] subNote = node.list();
			for(String filename : subNote){
				loadResourceReferences(new File(node, filename));
			}
		}else{
			String resourceRef = node.getPath().substring(node.getPath().indexOf("resources"), node.getPath().length());
			Log.info("### Resource found: "+resourceRef);
			resources.add(resourceRef);
		}
	}
	
	private boolean isExcluded(String key) {
		for(String excluded : EXCLUDED_RESOURCES)
			if(key.equals(excluded))return true;
		return false;
	}
	
	public static void main(String[] args) throws FileNotFoundException, IOException {
		new ResourceFinder().buildPropertiesFile("resource.properties");
	}
}
